import { ApiService, GitCommit, AIConfig } from './ApiService';
import { GitService } from './GitService';
import { AIProvider, MultiAIConfig } from '../types';

/**
 * 报告类型
 */
export type ReportType = 'daily' | 'weekly' | 'custom';

/**
 * 报告模板
 */
export interface ReportTemplate {
  id: string;
  name: string;
  type: ReportType;
  content: string;
  description?: string;
}

/**
 * 报告生成选项
 */
export interface ReportGenerationOptions {
  projectPath: string;
  type: ReportType;
  startDate?: string;
  endDate?: string;
  author?: string;
  style?: 'simple' | 'professional';
  format?: 'markdown' | 'text';
  includeDiff?: boolean;
  customPrompt?: string;
  aiConfig?: AIConfig;
  multiAIConfig?: MultiAIConfig;
  selectedCommits?: string[]; // Git自选模式的提交哈希列表
}

/**
 * 手动报告生成选项
 */
export interface ManualReportOptions {
  content: string;
  reportType: 'daily' | 'weekly';
  style: 'professional' | 'simple';
  enablePolish: boolean;
  format?: 'markdown' | 'text';
  customPrompt?: string;
  aiConfig?: AIConfig;
  multiAIConfig?: MultiAIConfig;
}

/**
 * 生成的报告
 */
export interface GeneratedReport {
  id: string;
  type: ReportType;
  title: string;
  content: string;
  summary?: string;
  projectPath: string;
  author?: string;
  dateRange: {
    start: string;
    end: string;
  };
  stats: {
    totalCommits: number;
    totalFiles: number;
    totalAdditions: number;
    totalDeletions: number;
    authors: string[];
  };
  generatedAt: string;
  aiConfig?: AIConfig;
}

/**
 * 报告生成服务
 */
export class ReportService {
  /**
   * 默认报告模板
   */
  private static readonly DEFAULT_TEMPLATES: ReportTemplate[] = [
    {
      id: 'daily-work',
      name: '日报模板',
      type: 'daily',
      content: `# 工作日报 - {{date}}

## 今日工作内容
{{commits_summary}}

## 代码提交统计
- 总提交数: {{total_commits}}
- 变更文件: {{total_files}}个
- 新增代码: {{total_additions}}行
- 删除代码: {{total_deletions}}行

## 详细提交记录
{{commits_detail}}

## 工作总结
{{ai_summary}}`,
      description: '用于生成日常工作日报'
    },
    {
      id: 'weekly-summary',
      name: '周报模板',
      type: 'weekly',
      content: `# 工作周报 - {{week_range}}

## 本周工作概览
{{commits_summary}}

## 本周代码统计
- 总提交数: {{total_commits}}
- 变更文件: {{total_files}}个
- 新增代码: {{total_additions}}行
- 删除代码: {{total_deletions}}行
- 参与人员: {{authors}}

## 主要工作内容
{{commits_detail}}

## 本周工作总结
{{ai_summary}}

## 下周计划
{{next_week_plan}}`,
      description: '用于生成每周工作总结'
    },
    {
      id: 'custom-report',
      name: '自定义报告',
      type: 'custom',
      content: `# 工作报告 - {{date_range}}

## 工作内容概览
{{commits_summary}}

## 代码变更统计
- 提交数量: {{total_commits}}
- 文件变更: {{total_files}}个
- 代码行数: +{{total_additions}} -{{total_deletions}}
- 贡献者: {{authors}}

## 详细工作记录
{{commits_detail}}

## 工作分析与总结
{{ai_summary}}`,
      description: '用于生成自定义时间范围的工作报告'
    }
  ];

  /**
   * 获取默认模板
   */
  static getDefaultTemplates(): ReportTemplate[] {
    return [...this.DEFAULT_TEMPLATES];
  }

  /**
   * 根据类型获取默认模板
   */
  static getDefaultTemplate(type: ReportType): ReportTemplate | null {
    return this.DEFAULT_TEMPLATES.find(t => t.type === type) || null;
  }

  /**
   * 生成手动输入的报告
   */
  static async generateManualReport(options: ManualReportOptions): Promise<{
    success: boolean;
    data?: string;
    error?: string;
  }> {
    try {
      if (!options.content.trim()) {
        return { success: false, error: '工作内容不能为空' };
      }

      // 检查AI配置
      let aiConfig: AIConfig | MultiAIConfig | null = null;
      
      // 优先使用多AI配置
      if (options.multiAIConfig && options.multiAIConfig.autoSwitch && options.multiAIConfig.models && options.multiAIConfig.models.length > 0) {
        aiConfig = options.multiAIConfig;
      } else if (options.aiConfig && options.aiConfig.apiKey) {
        aiConfig = options.aiConfig;
      }
      
      if (!aiConfig) {
        return { success: false, error: 'AI配置不完整' };
      }

      // 构建请求数据
      const requestData: any = {
        content: options.content,
        reportType: options.reportType,
        style: options.style,
        enablePolish: options.enablePolish,
        format: options.format || 'markdown',
        customPrompt: options.customPrompt,
        type: 'manual_report'
      };
      
      // 根据配置类型添加相应字段
      if ('models' in aiConfig) {
        // 多AI配置
        requestData.multiConfig = aiConfig;
      } else {
        // 单一AI配置
        requestData.model = aiConfig.model || 'deepseek-chat';
        requestData.apiKey = aiConfig.apiKey;
        requestData.aiConfig = {
          provider: aiConfig.provider || 'deepseek',
          baseUrl: aiConfig.baseUrl,
          temperature: aiConfig.temperature || 0.7,
          maxTokens: aiConfig.maxTokens || 2000
        };
      }

      console.log('[ReportService] 发送手动报告生成请求:', requestData);

      // 调用后端API
      const response = await fetch('http://localhost:3001/api/ai/reports/manual', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
      });

      if (!response.ok) {
        const errorData = await response.json();
        console.error('[ReportService] 手动报告生成失败:', errorData);
        return {
          success: false,
          error: errorData.error || `HTTP ${response.status}: ${response.statusText}`
        };
      }

      const result = await response.json();
      console.log('[ReportService] 手动报告生成成功:', result);

      return {
        success: true,
        data: result.content
      };
    } catch (error) {
      console.error('[ReportService] 手动报告生成失败:', error);
      return {
        success: false,
        error: `生成报告失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
    }
  }

  /**
   * 生成报告
   */
  static async generateReport(options: ReportGenerationOptions): Promise<{
    success: boolean;
    data?: GeneratedReport;
    error?: string;
  }> {
    try {
      // 1. 获取Git提交数据
      const commitsResult = await this.getCommitsForReport(options);
      if (!commitsResult.success || !commitsResult.data) {
        return { success: false, error: commitsResult.error || '获取提交数据失败' };
      }

      const commits = commitsResult.data;
      
      // 检查是否有提交数据
      if (!commits || commits.length === 0) {
        const reportTypeText = options.type === 'daily' ? '今日' : options.type === 'weekly' ? '本周' : '指定时间范围内';
        return {
          success: false,
          error: `${reportTypeText}没有Git提交记录，无法生成报告。请确认项目路径正确且在指定时间范围内有代码提交。`
        };
      }
      
      const stats = GitService.getCommitStats(commits);

      // 2. 准备模板和数据
      const template = this.getDefaultTemplate(options.type)?.content || '';
      const templateData = this.prepareTemplateData(commits, stats, options);

      // 3. 渲染基础模板
      let reportContent = this.renderTemplate(template, templateData);

      // 4. 使用AI增强报告内容
      let aiConfig: AIConfig | MultiAIConfig | null = null;
      
      // 优先使用多AI配置
      if (options.multiAIConfig && options.multiAIConfig.autoSwitch && options.multiAIConfig.models && options.multiAIConfig.models.length > 0) {
        aiConfig = options.multiAIConfig;
        console.log('[ReportService] 开始AI增强报告，使用多AI配置');
      } else if (options.aiConfig && options.aiConfig.apiKey && options.aiConfig.provider) {
        aiConfig = options.aiConfig;
        console.log('[ReportService] 开始AI增强报告，使用单一AI配置:', options.aiConfig);
      }
      
      if (aiConfig) {
        const aiResult = await this.enhanceReportWithAI(commits, reportContent, aiConfig, options.type, options.style, options.format, options.customPrompt);

        if (aiResult.success && aiResult.data) {
          console.log('[ReportService] AI增强成功');
          reportContent = aiResult.data.content;
        } else {
          console.warn('[ReportService] AI增强失败:', aiResult.error);
        }
      } else {
        console.log('[ReportService] 跳过AI增强，配置不完整');
      }

      // 5. 生成最终报告
      const report: GeneratedReport = {
        id: Date.now().toString(),
        type: options.type,
        title: this.generateReportTitle(options),
        content: reportContent,
        projectPath: options.projectPath,
        author: options.author,
        dateRange: this.getDateRange(options),
        stats: {
          totalCommits: stats.totalCommits,
          totalFiles: stats.totalFiles,
          totalAdditions: stats.totalAdditions,
          totalDeletions: stats.totalDeletions,
          authors: stats.authors
        },
        generatedAt: new Date().toISOString(),
        aiConfig: options.aiConfig
      };

      return { success: true, data: report };
    } catch (error) {
      return {
        success: false,
        error: `生成报告失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
    }
  }

  /**
   * 获取报告所需的提交数据
   */
  private static async getCommitsForReport(options: ReportGenerationOptions): Promise<{
    success: boolean;
    data?: GitCommit[];
    error?: string;
  }> {
    // Git自选模式：根据选定的提交哈希获取提交记录
    if (options.selectedCommits && options.selectedCommits.length > 0) {
      return GitService.getCommitsByHashes(
        options.projectPath,
        options.selectedCommits,
        options.includeDiff
      );
    }
    
    // 统一使用getDateRange计算日期范围，确保日期计算逻辑一致
    const dateRange = this.getDateRange(options);
    
    switch (options.type) {
      case 'daily':
      case 'weekly':
        return GitService.getCommitsByDateRange(
          options.projectPath,
          dateRange.start,
          dateRange.end,
          options.author,
          options.includeDiff
        );
      
      case 'custom':
        if (!options.startDate || !options.endDate) {
          return { success: false, error: '自定义报告需要指定开始和结束日期' };
        }
        return GitService.getCommitsByDateRange(
          options.projectPath,
          dateRange.start,
          dateRange.end,
          options.author,
          options.includeDiff
        );
      
      default:
        return { success: false, error: '不支持的报告类型' };
    }
  }

  /**
   * 验证日期字符串是否有效
   */
  private static isValidDate(dateStr: string): boolean {
    if (!dateStr) return false;
    const date = new Date(dateStr);
    return !isNaN(date.getTime());
  }

  /**
   * 安全地创建日期对象，如果无效则返回当前时间
   */
  private static safeCreateDate(dateStr: string): Date {
    if (this.isValidDate(dateStr)) {
      return new Date(dateStr);
    }
    console.warn(`[ReportService] 无效的日期字符串: ${dateStr}，使用当前时间`);
    return new Date();
  }

  /**
   * 准备模板数据
   */
  private static prepareTemplateData(
    commits: GitCommit[],
    stats: any,
    options: ReportGenerationOptions
  ): Record<string, string> {
    const now = new Date();
    const dateRange = this.getDateRange(options);
    
    // 安全地创建日期对象
    const startDate = this.safeCreateDate(dateRange.start);
    const endDate = this.safeCreateDate(dateRange.end);
    
    return {
      date: now.toLocaleDateString('zh-CN'),
      week_range: `${startDate.toLocaleDateString('zh-CN')} - ${endDate.toLocaleDateString('zh-CN')}`,
      date_range: `${startDate.toLocaleDateString('zh-CN')} - ${endDate.toLocaleDateString('zh-CN')}`,
      total_commits: stats.totalCommits.toString(),
      total_files: stats.totalFiles.toString(),
      total_additions: stats.totalAdditions.toString(),
      total_deletions: stats.totalDeletions.toString(),
      authors: stats.authors.join(', '),
      commits_summary: this.generateCommitsSummary(commits),
      commits_detail: GitService.formatCommitsForReport(commits),
      ai_summary: '[AI分析内容将在此处生成]',
      next_week_plan: '[下周计划将在此处生成]'
    };
  }

  /**
   * 渲染模板
   */
  private static renderTemplate(template: string, data: Record<string, string>): string {
    let result = template;
    
    Object.entries(data).forEach(([key, value]) => {
      const regex = new RegExp(`{{${key}}}`, 'g');
      result = result.replace(regex, value);
    });
    
    return result;
  }

  /**
   * 使用AI增强报告内容
   */
  private static async enhanceReportWithAI(
    commits: GitCommit[],
    baseContent: string,
    config: AIConfig | MultiAIConfig,
    reportType: ReportType,
    style?: 'simple' | 'professional',
    format?: 'markdown' | 'text',
    customPrompt?: string
  ): Promise<{ success: boolean; data?: { content: string }; error?: string }> {
    try {
      // 构建后端期望的请求参数格式
      let requestData: any = {
        commits,
        style: style || 'simple',
        format: format || 'markdown',
        customPrompt: customPrompt,
        type: reportType // 传递正确的报告类型
      };
      
      // 检查是否为多AI配置
      if ('models' in config && Array.isArray(config.models)) {
        // 多AI配置
        requestData.multiConfig = config;
        console.log('[ReportService] 使用多AI配置发送报告生成请求');
      } else {
        // 单一AI配置
        const singleConfig = config as AIConfig;
        requestData.model = singleConfig.model || 'deepseek-chat';
        requestData.apiKey = singleConfig.apiKey;
        requestData.aiConfig = {
          provider: singleConfig.provider || 'deepseek',
          baseUrl: singleConfig.baseUrl,
          temperature: singleConfig.temperature || 0.7,
          maxTokens: singleConfig.maxTokens || 2000
        };
        console.log('[ReportService] 使用单一AI配置发送报告生成请求');
      }
      
      console.log('[ReportService] 发送AI报告生成请求:', requestData);
      
      // 直接调用后端API
      const response = await fetch('http://localhost:3001/api/ai/reports/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        console.error('[ReportService] AI报告生成失败:', errorData);
        return {
          success: false,
          error: errorData.error || `HTTP ${response.status}: ${response.statusText}`
        };
      }
      
      const result = await response.json();
      console.log('[ReportService] AI报告生成成功:', result);
      
      return {
        success: true,
        data: { content: result.data?.content || result.content }
      };
    } catch (error) {
      console.error('[ReportService] AI增强失败:', error);
      return {
        success: false,
        error: `AI增强失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
    }
  }

  /**
   * 生成提交摘要
   */
  private static generateCommitsSummary(commits: GitCommit[]): string {
    if (!commits || commits.length === 0) {
      return '本期间内没有代码提交。';
    }

    const summary = [];
    
    // 按类型分类提交
    const categories = {
      feature: commits.filter(c => /^(feat|feature)/i.test(c.message)),
      fix: commits.filter(c => /^(fix|bugfix)/i.test(c.message)),
      docs: commits.filter(c => /^docs/i.test(c.message)),
      style: commits.filter(c => /^style/i.test(c.message)),
      refactor: commits.filter(c => /^refactor/i.test(c.message)),
      test: commits.filter(c => /^test/i.test(c.message)),
      other: commits.filter(c => !/^(feat|feature|fix|bugfix|docs|style|refactor|test)/i.test(c.message))
    };

    if (categories.feature.length > 0) {
      summary.push(`新功能开发 ${categories.feature.length} 项`);
    }
    if (categories.fix.length > 0) {
      summary.push(`问题修复 ${categories.fix.length} 项`);
    }
    if (categories.docs.length > 0) {
      summary.push(`文档更新 ${categories.docs.length} 项`);
    }
    if (categories.refactor.length > 0) {
      summary.push(`代码重构 ${categories.refactor.length} 项`);
    }
    if (categories.other.length > 0) {
      summary.push(`其他改动 ${categories.other.length} 项`);
    }

    return summary.length > 0 ? summary.join('，') + '。' : '完成了多项代码提交。';
  }

  /**
   * 生成报告标题
   */
  private static generateReportTitle(options: ReportGenerationOptions): string {
    const dateRange = this.getDateRange(options);
    const startDate = this.safeCreateDate(dateRange.start).toLocaleDateString('zh-CN');
    const endDate = this.safeCreateDate(dateRange.end).toLocaleDateString('zh-CN');
    
    switch (options.type) {
      case 'daily':
        return `工作日报 - ${startDate}`;
      case 'weekly':
        return `工作周报 - ${startDate} 至 ${endDate}`;
      case 'custom':
        return `工作报告 - ${startDate} 至 ${endDate}`;
      default:
        return '工作报告';
    }
  }

  /**
   * 获取日期范围
   */
  private static getDateRange(options: ReportGenerationOptions): { start: string; end: string } {
    const now = new Date();
    
    switch (options.type) {
      case 'daily':
        const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
        return {
          start: startOfDay.toISOString(),
          end: endOfDay.toISOString()
        };
      
      case 'weekly':
        const dayOfWeek = now.getDay(); // 0=周日, 1=周一, ..., 6=周六
        // 计算本周一的日期 - 如果是周日，往前推6天到周一；否则计算到周一的偏移
        const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
        const startOfWeek = new Date(now.getTime() + mondayOffset * 24 * 60 * 60 * 1000);
        startOfWeek.setHours(0, 0, 0, 0);
         
        // 计算本周日的日期 - 周报应该包含完整的一周数据（周一到周日）
        const sundayOffset = dayOfWeek === 0 ? 0 : 7 - dayOfWeek;
        const endOfWeek = new Date(now.getTime() + sundayOffset * 24 * 60 * 60 * 1000);
        endOfWeek.setHours(23, 59, 59, 999);
        
        return {
          start: startOfWeek.toISOString(),
          end: endOfWeek.toISOString()
        };
      
      case 'custom':
        // 验证并处理自定义日期
        let startDate = options.startDate;
        let endDate = options.endDate;
        
        // 如果日期无效，使用当前时间
        if (!this.isValidDate(startDate)) {
          console.warn(`[ReportService] 无效的开始日期: ${startDate}，使用当前时间`);
          startDate = now.toISOString();
        } else {
          // 确保日期格式为ISO字符串
          const parsedStartDate = new Date(startDate);
          startDate = parsedStartDate.toISOString();
        }
        
        if (!this.isValidDate(endDate)) {
          console.warn(`[ReportService] 无效的结束日期: ${endDate}，使用当前时间`);
          endDate = now.toISOString();
        } else {
          // 确保日期格式为ISO字符串
          const parsedEndDate = new Date(endDate);
          endDate = parsedEndDate.toISOString();
        }
        
        return {
          start: startDate,
          end: endDate
        };
      
      default:
        return {
          start: now.toISOString(),
          end: now.toISOString()
        };
    }
  }
}